process.env.NODE_ENV = 'dev'
const path = require('path')
const { access } = require('./src/util/log')
const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const { Agent } = require('http')
// 获取cookie过期时间
const getCookieExpires = () => {
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    return d.toGMTString()
}
// 解析cookie
const SESSION_DATA = {}
// 处理post数据
const getPostData = req => {
    const promise = new Promise((resolve, reject) => {
        if (req.method !== "POST") {
            resolve({
                post: false
            });
            return;
        }
        if (req.headers["content-type"] !== "application/json") {
            resolve({
                "content-type": "false"
            });
            return;
        }
        let postData = "";
        req.on("data", chunk => {
            postData += chunk.toString();
        });
        // console.log(postData);
        req.on("end", () => {
            if (!postData) {
                resolve({
                    postData: "false"
                });
                return;
            }
            resolve(JSON.parse(postData));
        });
    });
    return promise;
};


const serverHandle = (req, res) => {
    access(`${req.method}--${req.url}--${req.headers['user-agent']}--${Date.now()}`)
    res.setHeader('Content-type', 'application/json')
    const url = req.url
    req.path = url.split('?')[0]
    req.query = querystring.parse(url.split('?')[1])

    // 解析cookie
    req.cookie = {}
    const cookieStr = req.headers.cookie || ''
    cookieStr.split(';').forEach((item) => {
        if (!item) {
            return
        }
        const arr = item.split('=')
        const key = arr[0]
        const val = arr[1]
        req.cookie[key] = val
    })

    let needSetCookie = false;
    let userId = req.cookie.userid;
    if (userId) {
        if (!SESSION_DATA[userId]) {
            SESSION_DATA[userId] = {};
        }
    } else {
        needSetCookie = true;
        userId = `${Date.now()}_${Math.random()}`;
        SESSION_DATA[userId] = {};
    }
    req.session = SESSION_DATA[userId];


    getPostData(req).then(postData => {
        // 接收客户端数据
        req.body = postData
        const blogResult = handleBlogRouter(req, res)
        if (blogResult) {
            blogResult.then(blogData => {
                if (needSetCookie) {
                    res.setHeader('set-cookie', `userid=${userId};  path = '/'; httpOnly; expires=${getCookieExpires()}`)
                }
                res.end(
                    JSON.stringify(blogData)
                )
            })
            return
        }
        // 处理blog路由
        // const blogData = handleBlogRouter(req, res)
        // if (blogData) {
        //     res.end(
        //         JSON.stringify(blogData)
        //     )
        //     return
        // }
        // 处理登录路由
        // const userData = handleUserRouter(req, res)
        // if (userData) {
        //     res.end(JSON.stringify(userData))
        //     return
        // }
        const userResult = handleUserRouter(req, res);
        if (userResult) {
            userResult.then(userData => {
                if (needSetCookie) {
                    res.setHeader(
                        "Set-Cookie",
                        `userid=${userId};path='/';httpOnly;expires=${getCookieExpires()}`
                    );
                }
                res.end(JSON.stringify(userData));
            });
            return;
        }
        res.writeHead('404', { 'Content-type': 'text/plain' })
        res.write('404notfound\n')
        res.end()
    })
}



module.exports = serverHandle